package cluster

import (
	"gomod.alauda.cn/mysql-mgr-operator/pkg/constant"
	"time"
)

type RestartOption struct {
}

type Restart struct {
	*RestartOption
	*Base
}

func NewRestart(opt *RestartOption) *Restart {
	return &Restart{
		RestartOption: opt,
	}
}

func (r *Restart) WithBase(base *Base) *Restart {
	r.Base = base
	return r
}

func (r *Restart) Run() error {
	switch r.Type {
	case TypeMysql:
		return r.restartMysql()
	case TypeMgr:
		return r.restartMgr()
	default:
		err := r.restartMysql()
		if err != nil {
			return r.restartMgr()
		}
	}
	return nil
}

func (r *Restart) restartMysql() error {
	cr, err := r.getMysqlCr()
	if err != nil {
		return err
	}
	now := time.Now().Format(time.RFC3339)
	cr.Annotations[constant.RestartTrigger] = now
	err = r.update(cr)
	if err != nil {
		return err
	}
	return nil
}

func (r *Restart) restartMgr() error {
	cr, err := r.getMgrCr()
	if err != nil {
		return err
	}
	now := time.Now().Format(time.RFC3339)
	cr.Annotations[constant.RestartTrigger] = now
	err = r.update(cr)
	if err != nil {
		return err
	}
	return nil
}
